package com.zou.demo.bootstrapcurd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zou.demo.bootstrapcurd.common.Result;
import com.zou.demo.bootstrapcurd.common.ResultUtil;
import com.zou.demo.bootstrapcurd.mapper.LoginUserMapper;
import com.zou.demo.bootstrapcurd.model.LoginUser;
import com.zou.demo.bootstrapcurd.service.LoginUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author: 邹祥发
 * @date: 2021/5/31 16:16
 * 用户管理信息列表
 */
@Controller
public class LoginUserController {

    @Resource
    private LoginUserMapper loginUserMapper;
    @Resource
    private LoginUserService loginUserService;

    //解决删除数据后的中重定向问题
    @RequestMapping(value = {"/loginUser", "/delUser/loginUser"}, method = RequestMethod.GET) //访问某url时
    public String loginU(Model model,
                         HttpSession session) {
        //获取登录的用户名
        String loginNames = (String) session.getAttribute("loginUser");
        //判断登录的用户名是否为管理员
        Integer permission = loginUserMapper.selectPermission(loginNames);
        if (permission.equals(1)) {
            //跳转到管理员界面
            List<LoginUser> users = loginUserMapper.selectLoginUser();
            model.addAttribute("users", users);//若不为空，写入域内
            return "loginUser";
        } else {
            //提示用户无权限操作
            return "noPermission";
        }
    }

    //修改方法（跳转页面）
    @RequestMapping(value = "/updateUser", method = RequestMethod.GET)
    public String up(Integer id, Model model) throws Exception {
        System.out.println("请求修改方法");
        System.out.println(id);
        //通过id查询对应的用户信息
        LoginUser editUser = loginUserMapper.selectUserById(id);
        model.addAttribute("editUser", editUser);

        return "updateUser";
    }

    //修改方法（更新数据）
    @RequestMapping(value = "/editUsers", method = RequestMethod.POST)
    public String edit(@RequestParam("id") Integer id,
                       @RequestParam("loginName") String loginName,
                       @RequestParam("loginPwd") String loginPwd,
                       @RequestParam("permission") Integer permission) {

        LoginUser loginUser = new LoginUser();
        loginUser.setId(id);
        loginUser.setLoginName(loginName);
        loginUser.setLoginPwd(loginPwd);
        loginUser.setPermission(permission);
        loginUserMapper.updateUser(loginUser);

        return "redirect:loginUser";
    }

    //删除方法
    @RequestMapping(value = "/delUser", method = RequestMethod.GET)
    public String del(Integer id) throws Exception {
        loginUserMapper.del(id);

        //必须重定向到 /loginUser,否则报404,因为loginUser有两个访问路径
        return "redirect:/loginUser";
    }

    //添加方法（跳转页面）
    //解决删除数据后的中重定向问题
    @RequestMapping(value = {"/addUser", "/delUser/addUser"})
    public String add() {
        return "addUser";
    }

    /**
     * 分页查询
     */
    @PostMapping("/pageList")
    @ResponseBody
    public Result<IPage<LoginUser>> pageList(@RequestParam(value = "loginName", required = false) String loginName,
                                    @RequestParam(defaultValue = "1") Integer pageNo,
                                    @RequestParam(defaultValue = "3") Integer pageSize) {
        // 构造查询条件
        QueryWrapper<LoginUser> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(loginName)) {
            queryWrapper.like("loginName", loginName);
            queryWrapper.orderByDesc("qq");
        }
        Page<LoginUser> page = new Page<>(pageNo, pageSize);

        IPage<LoginUser> result = loginUserService.page(page, queryWrapper);
        // 设置总记录数
        result.setTotal(loginUserService.count(queryWrapper));

        return ResultUtil.ok(result);
    }

    //添加方法（设置数据）
    @RequestMapping(value = "/addUsers", method = RequestMethod.POST)
    public String add(String loginName, String loginPwd, Integer permission, Model model) throws Exception {

        //用户名不存在
        if (loginUserMapper.selectName(loginName) == null) {
            LoginUser user = new LoginUser();
            user.setLoginName(loginName);
            user.setLoginPwd(loginPwd);
            user.setPermission(permission);
            loginUserMapper.insertUser(user);

            return "redirect:loginUser";
        } else {
            model.addAttribute("msg", "用户名已存在！");
            return "addUser";
        }
    }

    //修改用户信息页（跳转页面）
    @RequestMapping(value = "/userInfo", method = RequestMethod.GET)
    public String userInfo(Model model, HttpSession session) throws Exception {
        //通过session获取登录的用户名
        String name = (String) session.getAttribute("loginUser");
        System.out.println(name);
        //根据用户名查找该用户的详细信息
        LoginUser userIn = loginUserMapper.selectUserByName(name);
        model.addAttribute("userIn", userIn);

        return "userInfo";
    }

    //修改方法（更新数据）
    @RequestMapping(value = "/editUserInfo", method = RequestMethod.POST)
    //loginName必须设置成required = false，否则报400
    public String edit(@RequestParam("qq") String qq,
                       @RequestParam("wechat") String wechat,
                       @RequestParam("blog") String blog,
                       @RequestParam("github") String github,
                       @RequestParam("hobby") String hobby,
                       HttpSession session) {
        //通过session获取登录的用户名
        String name = (String) session.getAttribute("loginUser");
        //根据用户名查找该用户的详细信息
        LoginUser loginUser = new LoginUser();
        loginUser.setLoginName(name);
        loginUser.setQq(qq);
        loginUser.setWechat(wechat);
        loginUser.setBlog(blog);
        loginUser.setGithub(github);
        loginUser.setHobby(hobby);

        loginUserMapper.updateUserInfo(loginUser);

        return "redirect:userInfo";
    }

    //修改用户密码页（跳转页面）
    @RequestMapping(value = "/editPassword", method = RequestMethod.GET)
    public String editPassword() {
        return "editPassword";
    }

    //修改密码方法（更新数据）
    @RequestMapping(value = "/editPwd", method = RequestMethod.POST)
    public String editPwd(@RequestParam("primaryPwd") String primaryPwd,
                          @RequestParam("newPwd") String newPwd,
                          @RequestParam("reNewPwd") String reNewPwd,
                          HttpSession session, Model model,
                          SessionStatus sessionStatus) {
        //通过session获取登录的用户名
        String name = (String) session.getAttribute("loginUser");
        //根据用户名查找该用户的密码
        String password = loginUserMapper.selectPwdByName(name);
        //用户输入的原密码与数据库密码一致
        if (primaryPwd.equals(password)) {
            //用户输入的新密码与原密码不相同
            if (!primaryPwd.equals(newPwd)) {
                //用户两次输入的新密码一致
                if (newPwd.equals(reNewPwd)) {
                    //通过用户名修改密码
                    loginUserMapper.editPwd(newPwd, name);
                    //清除session
                    session.invalidate();
                    sessionStatus.setComplete();

                    return "login";
                } else {
                    //两次输入的密码不一致
                    model.addAttribute("msg", "两次输入的新密码不一致！");
                }
            } else {
                //新密码与原密码相同
                model.addAttribute("msg", "新密码不能与原密码相同！");
            }
        } else {
            //用户输入的原密码错误
            model.addAttribute("msg", "原密码错误！");
        }

        return "editPassword";
    }

}